#-------------------------------------------------------------------------------
# Name:        file_split.py
# Purpose:     ?????????
#
# Author:      Lotte
#
# Created:     12/08/2012
# Copyright:   (c) Lotte 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import os,sys

def get_serial_name(filename, index, out_path):
    name = os.path.basename(filename)
    a = os.path.splitext(name)
    return out_path + "/%s_%04i%s" % ( a[0], index, a[1] )

def split(filename,size_byte,out_path):
    mb = 1048576  # 1024 * 1024 = 1048576

    try:
        src_file = open(filename,"rb")
    except IOError:
        print "file(" + filename + ") not exist\r\n"
        exit(0)

    src_file_size = os.path.getsize(filename)

    if long(size_byte) >= src_file_size :
        return False

    if os.path.exists(out_path) == False :
        os.makedirs(out_path)

    part_size = size_byte
    left_size = src_file_size

    if part_size > mb:
        part_size = mb

    index = 0
    while left_size > 0:
        data_writen = 0
        currfile = open( get_serial_name(filename, index, out_path), "wb")
        index = index + 1

        while left_size > 0:
            read_size = size_byte - data_writen
            if read_size >= mb:
                data = src_file.read(mb)
                currfile.write(data)
                left_size -= mb
                data_writen += mb
            else:
                data = src_file.read(read_size)
                currfile.write(data)
                left_size -= read_size
                currfile.close()
                break  #this part ok
    src_file.close()
    return True



def main():
    #print get_serial_name("abc.d",1)
    if len(sys.argv) < 4:
        print "cmd format: file_split filename part_size[m] out_path\r\n"
        exit(0)

    filename = sys.argv[1]
    out_path = sys.argv[3]
    index = sys.argv[2].find("m")
    if  index < 0:
        size = sys.argv[2]
    else:
        size = long(sys.argv[2][0:index]) * 1024 * 1024

    if split(filename,size,out_path) == True:
        print "file splited\r\n"
    else:
        print "error occured during file split\r\n"


if __name__ == '__main__':
    main()
